package com.example.tao.smartcar.wifi.LAN;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.nfc.Tag;
import android.util.Log;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by Tao on 2016/8/29.
 */
public class WifiTool {
    private static final String TAG = "WifiTool";

    private static final int CORE_POOL_SIZE = 1;
    private static final int MAX_POOL_SIZE = 255;

    private WifiManager mWifiManage;
    private WifiInfo mWifiInfo;
    private List<ScanResult> mWifiList;
    private List<WifiConfiguration> mWifiConfigurationList;

    private String mDevAddress;
    private String mLocAddress;
    private String mAPAddress;
    private Runtime mRuntime = Runtime.getRuntime();
    private Process mProcess = null;
    private String mPing = "ping -c 1 -w 3 ";
    private List<String> mIpList = new ArrayList<String>();
    private ThreadPoolExecutor mExecutor;

    public WifiTool(Context context) {
        mWifiManage = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        mWifiInfo = mWifiManage.getConnectionInfo();
    }

    /**
     * 打开WIFI
     */
    public void openWifi() {
        if (!mWifiManage.isWifiEnabled())
            mWifiManage.setWifiEnabled(true);
    }

    /**
     * 扫描WIFI
     */
    public void scanWifi(){
        mWifiManage.startScan();
        mWifiList = mWifiManage.getScanResults();
        mWifiConfigurationList = mWifiManage.getConfiguredNetworks();

        String ssid = mWifiList.get(0).SSID;
    }


    /**
     * 获取扫描到的WIFI
     * @return
     */
    public List<ScanResult> getWifiList() {

        return mWifiList;
    }

    /**
     * 获取扫描到的WIFI SSID
     * @return
     */
    public List<String> getWifiSsidList() {
        List<String> wifiSsidList = new ArrayList<String>();
        for (int i = 0; i < mWifiList.size(); i++)
            wifiSsidList.add(mWifiList.get(i).SSID);
        return wifiSsidList;
    }

    /**
     * 判断该wifi是否连接过
     * @param ssid
     * @return
     */
    public boolean isConfiged(String ssid) {
        for (int i = 0; i < mWifiConfigurationList.size(); i++) {
            int wifiId = -1;
            WifiConfiguration wifiConfiguration = mWifiConfigurationList.get(i);
            if (wifiConfiguration.SSID.equals(ssid)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 连接WIFI
     * @param ssid
     * @return
     */
    public boolean connectWifi(String ssid) {
        for (int i = 0; i < mWifiConfigurationList.size(); i++) {
            int wifiId = -1;
            WifiConfiguration wifiConfiguration = mWifiConfigurationList.get(i);
            if (wifiConfiguration.SSID.equals("\"" + ssid + "\"")) {
                wifiId = wifiConfiguration.networkId;
                if (wifiId != -1) {
                    int cnt = 0;
                    while (!(mWifiManage.enableNetwork(wifiId, true))) {
                        cnt++;
                        if (cnt == 1000)
                            return false;
                    }
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 连接wifi
     * @param ssid
     * @param password
     * @return
     */
    public boolean connectWifi(String ssid, String password) {
        //if (connectWifi(ssid) == true)
        //    return true;
        int wifiId = -1;
        for (int i = 0; i < mWifiList.size(); i++) {
            ScanResult wifi = mWifiList.get(i);
            if (wifi.SSID.equals(ssid)) {
                WifiConfiguration wifiConfiguration = new WifiConfiguration();
                wifiConfiguration.SSID = "\"" + wifi.SSID + "\"";
                if ((password != null) && (password.length() > 0))
                    wifiConfiguration.preSharedKey = "\"" + password + "\"";
                else
                    wifiConfiguration.preSharedKey = null;
                wifiConfiguration.hiddenSSID = false;
                wifiConfiguration.status = WifiConfiguration.Status.ENABLED;
                wifiId = mWifiManage.addNetwork(wifiConfiguration);
                if (wifiId != -1) {
                    int cnt = 0;
                    while (!(mWifiManage.enableNetwork(wifiId, true))) {
                        cnt++;
                        if (cnt == 1000)
                            return false;
                    }
                    return true;
                }
            }
        }
        return false;
    }

    public String getAPAddress() {
        mDevAddress = getDeviceAddress();
        mLocAddress = getLocalAddress(mDevAddress);
        mAPAddress = mLocAddress + 1;
        return mAPAddress;
    }

    public void scanOtherSTAs() {
        mDevAddress = getDeviceAddress();
        mLocAddress = getLocalAddress(mDevAddress);

        mIpList.clear();

        mExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, 2000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(CORE_POOL_SIZE));

        for (int i = 0; i < 255; i++) {
            final int lastAddress = i;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    String ping = WifiTool.this.mPing + mLocAddress + lastAddress;
                    //Log.d(TAG, "ping " + ping);
                    String currentIp = mLocAddress + lastAddress;
                    if (currentIp.equals(mDevAddress))
                        return;

                    try {
                        mProcess = mRuntime.exec(ping);
                        int result = mProcess.waitFor();
                        if (result == 0) {
                            mIpList.add(currentIp);
                            Log.d(TAG, "ping " + currentIp + " OK");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        if (mProcess != null)
                            mProcess.destroy();
                    }
                }
            };

            mExecutor.execute(runnable);
        }

        mExecutor.shutdown();
        Log.d(TAG, "mExecutor.shutdown()");

        while (true) {
            try {
                if (mExecutor.isTerminated()) {
                    Log.d(TAG, "扫描结束，总共扫描到" + mIpList.size() + "个设备");
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public void destory() {
        if (mExecutor != null)
            mExecutor.shutdownNow();
    }


    private String getDeviceAddress() {
        String ipAddress = "";
        try {
            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
            while (enumeration.hasMoreElements()) {
                NetworkInterface networkInterface = enumeration.nextElement();
                Enumeration<InetAddress> address = networkInterface.getInetAddresses();
                while (address.hasMoreElements()) {
                    InetAddress ip = address.nextElement();
                    if ((!ip.isLoopbackAddress()) && (ip instanceof Inet4Address)) {
                        ipAddress = ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ipAddress;
    }


    private String getLocalAddress(String devAddress) {
        if ((!devAddress.equals("")) && (devAddress != null)) {
            return devAddress.substring(0, devAddress.lastIndexOf(".") + 1);
        }
        return null;
    }

    public List<String> getIpList() {
        return mIpList;
    }
}
